<template>
  <!-- 表格 -->
  <el-card shadow="never" :body-style="{ padding: '10px' }">
    <div style="margin-bottom:12px;">
      <el-button type="primary" @click="open = true">添加分组</el-button>
    </div>
    <el-table size="large" :data="tableData.rows" :header-cell-style="{
      backgroundColor: '#ccddff', color: '#515a6e', fontWeight: 'normal'
    }">
      <!-- 直接渲染数据 -->
      <el-table-column prop="_id" label="ID" width="250" />
      <el-table-column prop="name" label="分组" />
      <!-- 需要往当前列中插入其他标签、或需要对数据进行其他处理时 -->
      <el-table-column label="操作" width="200" align="center">
        <!-- 以插槽的方式插入其它标签 -->
        <template #default="scope">
          <el-button type="primary" text @click="openUpdateDialog(scope.row)">
            修改
          </el-button>
          <el-button type="primary" text @click="deleteconfirm(scope.row._id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页 -->
    <div class="page-container">
      <el-pagination v-model:current-page="pageData.currentPage" v-model:page-size="pageData.pageSize"
        :page-sizes="[10, 200, 300, 400]" :background="true" layout="total, 
        sizes, prev, pager, next, jumper" :total="tableData.total" />
    </div>
  </el-card>

  <!-- 弹窗 -->





  <el-dialog v-model="open" :title="dialogTitle" width="500" destroy-on-close>
    <!-- // destroy-on-close:表示当关闭时，销毁其中的元素 -->
    <el-form ref="ruleFormRef" :model="groupItem" :rules="rules" label-width="auto" status-icon>
      <el-form-item label="分组名称" prop="name">
        <el-input v-model="groupItem.name" placeholder="请输入分组名称" />
      </el-form-item>
    </el-form>


    <!-- 弹窗的右下角的按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="handleok">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import type { FormRules } from 'element-plus'
import { onMounted } from 'vue';
//  import axios from 'axios';
// import instance from '../../../utils/axiosConfig';
// import http from '../../../utils/http';
// import api from '@/api';
import api from '@/api';
import { ElMessage, ElMessageBox } from 'element-plus'
// import usergroupitem
import { usergroupitem } from '@/api/modules/AuserGroups';
//发送请求
onMounted(() => {
  getGroupData();

})
//引入 axios
interface RuleForm {
  name: string

}

// interface UserGroupItem {
//   _id: string;
//   name: string;
// }


let open = ref(false);
//表单双向数据绑定的对象
let groupItem = ref<usergroupitem>({ _id: '', name: '' })
//定义表单的验证规则
let rules = reactive<FormRules<RuleForm>>({
  //针对表单中的name属性，来验证规则
  name: [
    //必填项
    { required: true, message: '分组名称不能为空', trigger: 'blur' },
  ],

});

let tableData = reactive({
  rows: [],
  total: 0
})



let pageData = ref({
  currentPage: 1,
  pageSize: 10
})
let dialogTitle = computed(() => {
  if (groupItem.value._id) {
    return '修改分组'
  }
  return '新增分组'
})


//侦听弹窗状态
watch(open, () => {
  if (!open.value) {
    groupItem.value = { _id: '', name: '' };
  }
})



let openUpdateDialog = (item:usergroupitem) => {
  open.value = true;
  //将要修改的数据回显到表单中
  // console.log(item);
  groupItem.value = { ...item };

}

watch(pageData, () => {

  getGroupData();
}, {
  deep: true
})




const getGroupData = async () => {
  const res = await api.AuserGroups.search(pageData.value);


  if (res.code == 200) {
    console.log(res.data.rows);
    tableData.rows = res.data.rows;
    tableData.total = res.data.total;
  }
}

let handleok = () => {
  if (groupItem.value._id) {
    handleupdate();
  } else {
    handleAdd();
  }
}


//新增
let handleAdd = async () => {
  //获取到要新增的数据
  //发送新增请求，将数据传递给后端
  let res = await api.AuserGroups.add({
    name: groupItem.value.name
  });
  //  console.log(res);
  if (res.code == 200) {
    open.value = false;
    getGroupData()
    ElMessage({
      message: '用户分组新增成功！',
      type: 'success',
    })

  } else {
    ElMessage.error('res.message')
  }
}



//修改
let handleupdate = async () => {
  let res = await api.AuserGroups.update(groupItem.value);
  if (res.code == 200) {
    open.value = false;
    getGroupData();
    ElMessage({
      message: '用户分组新增成功！',
      type: 'success',
    })
  } else {
    ElMessage.error('res.message')
  }

}


//确认前删除
let deleteconfirm = (_id: string) => {
  ElMessageBox.confirm(
    '数据删除后不可恢复，确认删除',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      //确认删除
      handledelete(_id)
    })

    .catch(() => { })


}

//删除
let handledelete = (_id: string) => {
  api.AuserGroups.remove({
    _id
  }).then(res => {
    // console.log(res);
    if (res.code == 200) {
      ElMessage.success('用户删除成功');
      getGroupData()
    } else {
      ElMessage.error(res.message)
    }

  })
}







</script>
<style scoped>
.page-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
